<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="csmType" style="width: 170px; margin-right: 2px;">
          <el-option label="客户电话" value="csmPhone" />
          <el-option label="客户编号" value="csmCode" />
          <el-option label="客户名称" value="csmName" />
          <el-option label="登记人" value="answer" />
          <el-option label="投诉内容" value="complainContent" />
          <el-option label="投诉订单" value="orderCode" />
          <el-option label="被投诉人" value="complainUserName" />
        </el-select>
        <el-input v-model.trim="csmText" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="处理机构:" prop="orgSNNo">
        <el-tree-select
          ref="treeSelect1"
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            filterable:true,
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
          @search-clear="searchClear"
        />
      </el-form-item>
      <el-form-item label="处理人:" prop="userId">
        <el-select v-model="query.userId" :loading="$loadingPlugin.getOwnersList" clearable filterable style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in ownersList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属机构:" prop="csmOrgSNNo">
        <el-tree-select
          ref="treeSelect"
          v-model="query.csmOrgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            filterable:true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @search-clear="searchClear"
        />
      </el-form-item>
      <el-form-item :table-form-merge="2" label="登记时间:" prop="createTime">
        <el-date-picker
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd HH:mm"
          unlink-panels
          :default-time="['00:00:00', '23:59:59']"
          :clearable="false"
        />
      </el-form-item>
      <el-form-item label="状态:" prop="cstatus">
        <el-select v-model="query.cstatus" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in complaintStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="回访结果:" prop="callResult">
        <el-select v-model="query.callResult" clearable filterable placeholder="请选择">
          <el-option
            v-for="item in visitStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="回访调查:" prop="callCheck">
        <el-select v-model="callCheck" multiple filterable placeholder="请选择">
          <el-option
            v-for="item in callCheckMap"
            :key="item.backVisitDesc"
            :label="item.backVisitDesc"
            :value="item.backVisitDesc"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="来源:" prop="fromPlat">
        <el-select v-model="query.fromPlat" filterable placeholder="请选择" clearable>
          <el-option
            v-for="item in fromPlatMap"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="投诉类型:" prop="complainType">
        <el-select v-model="query.complainType" filterable placeholder="请选择" clearable>
          <el-option
            v-for="item in complaintTypeList"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="1" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button v-permission="9" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      v-loading="$loadingPlugin.fetchData"
      border
      class="complaintLbTable"
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      :row-class-name="tableRowClassName"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <csm-detail ref="csmDetail" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymenFilList" />
    <detail ref="detail" @openPressOrder="openPressOrder" @openTransferOrder="openTransferOrder" @dealConfirm="dealConfirm" @openReturnVisit="openReturnVisit" @openBackOrder="openBackOrder" @openRemark="openRemark" />
    <deal-confirm ref="dealConfirm" />
    <transfer-order ref="transferOrder" />
    <press-order ref="pressOrder" />
    <remark-order ref="remarkOrder" />
    <back-order ref="backOrder" />
    <return-visit ref="returnVisit" :visit-status-map="visitStatusMap" :tree-data="treeData" />
    <flow-info ref="flowInfo" />
    <backOrderConfirm ref="backOrderConfirm" />
    <complaintDetail ref="complaintDetail" :complaint-type-list="complaintTypeList" :complaint-status-map="complaintStatusMap" @openPressOrder="openPressOrder" @openTransferOrder="openTransferOrder" @dealConfirm="dealConfirm" @openReturnVisit="openReturnVisit" @openBackOrder="openBackOrder" @openRemark="openRemark" @openBackOrderConfirm="openBackOrderConfirm" />
  </div>
</template>

<script>
  import {
    queryComplaintManageList,
    queryExportComplaintList, queryComplaintReturnVisitParams, queryMap, getComplainType, getComplainStatus, complainUserList
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import moment from 'dayjs'
  import Detail from './components/Detail'
  import DealConfirm from './components/DealConfirm'
  import TransferOrder from './components/TransferOrder'
  import PressOrder from '../../components/PressOrderComplaint'
  import RemarkOrder from './components/RemarkOrderModal'
  import BackOrder from './components/BackOrder'
  import BackOrderConfirm from './components/BackOrderConfirm'
  import ReturnVisit from './components/ReturnVisit'
  import FlowInfo from '../../components/FlowInfoCommon'
  import CsmDetail from '../../components/CsmDetailModal/index.vue'
  import complaintDetail from './components/complaintDetail.vue'

  const colorObj = {
    1: 'color:#ff0000;',
    2: 'color:#330066;',
    3: 'color:#0066ff;'
  }

  export default {
    name: 'complaintManage',
    components: {
      Detail, DealConfirm, TransferOrder, PressOrder, RemarkOrder, BackOrder, ReturnVisit, FlowInfo, CsmDetail,
      BackOrderConfirm, complaintDetail
    },
    data() {
      return {
        actionColWidth: 80,
        treeData: [],
        complaintStatusMap: [],
        visitStatusMap: [
          {
            value: 1,
            desc: '满意'
          },
          {
            value: 2,
            desc: '不满意'
          },
          {
            value: 3,
            desc: '未回访'
          }
        ],
        callCheckMap: [

        ],
        ownersList: [],
        calcTypeList: [],
        paymenFilList: [],
        csmType: 'csmPhone',
        date: [moment().startOf('day'), moment().endOf('day')],
        csmText: '',
        callCheck: [],
        query: {
          orgSNNo: '',
          userId: '',
          csmOrgSNNo: '',
          cstatus: '',
          callResult: '',
          fromPlat: '',
          complainType: ''
        },
        complaintTypeList: [],
        roleTypeList: [],
        commonKeysInfoList: [],
        fromPlatMap: [
          {
            value: 1,
            label: '呼叫中心'
          },
          {
            value: 7,
            label: '话务下单'
          }
        ],
        searchParams: {},
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData', 'exportDomain'
      ]),
      column: function() {
        return [
          {
            type: 'index'
          },
          {
            prop: 'complainCode',
            label: '投诉单号',
            width: 160,
            render: (h, { row }) => (
              <el-link underline={false} onClick={() => this.openComplaintDetail(row)}>
                {row.complainCode}
              </el-link>
            )
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 110,
            render: (h, { row }) => (
              <el-link underline={false} onClick={() => this.openCsmDetail(row)}>
                {row.csmCode}
              </el-link>
            )
          },
          {
            prop: 'csmName',
            label: '客户名称'
          },
          {
            prop: 'csmPhone',
            width: 120,
            label: '客户电话'
          },
          {
            prop: 'csmAddress',
            width: 200,
            label: '客户地址'
          },
          {
            prop: 'csmOrgName',
            label: '所属机构',
            minWidth: 160,
            showOverflowTooltip: true
          },
          {
            prop: 'orgName',
            label: '处理机构',
            width: 110
          },
          {
            prop: 'userName',
            label: '处理人'
          },
          {
            prop: 'operateDt',
            label: '处理时间',
            width: 160,
            render: (h, { row }) => <span>{ row.operateDt && parseTime(row.operateDt, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'complainContent',
            width: 160,
            label: '投诉内容'
          },
          {
            prop: 'remark',
            label: '备注',
            width: 110
          },
          {
            prop: 'marker',
            label: '处理结果',
            width: 110
          },
          {
            prop: 'callUserName',
            label: '回访人'
          },
          {
            prop: 'callTime',
            label: '回访时间',
            width: 160,
            render: (h, { row }) => <span>{ row.callTime && parseTime(row.callTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'callResult',
            label: '回访结果',
            render: (h, { row }) => <span>{ row.callResult ? formatColumnMap(this.visitStatusMap, 'value', row.callResult, 'desc') : '' }</span>
          },
          {
            prop: 'cstatus',
            label: '状态',
            width: 110,
            render: (h, { row }) => <span style={colorObj[row.cstatus]}>{ row.cstatus ? formatColumnMap(this.complaintStatusMap, 'value', row.cstatus, 'desc') : '未支付' }</span>
          },
          // {
          //   prop: 'callCheck',
          //   width: 150,
          //   label: '回访调查',
          //   showOverflowTooltip: true,
          //   render: (h, { row }) => {
          //     const temp = []
          //     let arr = []
          //     if (row.callCheck) arr = row.callCheck.split(',')
          //     if (arr.length > 0) {
          //       arr.forEach(item => {
          //         const match = this.commonKeysInfoList.find(it => Number(it.keyId) === Number(item))
          //         if (match) temp.push(match.keyName)
          //       })
          //     }
          //     return <span>{temp.join(',')}</span>
          //   }
          // },
          {
            prop: 'backVisitDesc',
            width: 120,
            label: '回访处理说明'
          },
          {
            prop: 'answer',
            label: '登记人'
          },
          {
            prop: 'createTime',
            label: '登记时间',
            width: 160,
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}') }</span>
          },
          {
            prop: 'fromPlatName',
            label: '单据来源',
            width: 110
          },
          {
            prop: 'complainType',
            label: '投诉类型',
            width: 110,
            render: (h, { row }) => <span>{ row.complainType ? formatColumnMap(this.complaintTypeList, 'value', row.complainType, 'desc') : '' }</span>

          },
          {
            prop: 'overTimeStaus',
            label: '超时状态',
            width: 110,
            formatter(row) {
              return row && row.overTimeStaus === 1 ? '未超时' : row.overTimeStaus === 2 ? '已超时' : ''
            }
          },
          {
            prop: 'orderCode',
            label: '投诉订单',
            width: 110
          },
          {
            prop: 'complainUserName',
            label: '被投诉人',
            width: 110
          },
          {
            label: '操作',
            align: 'center',
            fixed: 'right',
            className: 'action-col',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
                <div>
                  <el-dropdown>
                    <span class='el-dropdown-link'>
                      更多<i class='el-icon-arrow-down el-icon--right'></i>
                    </span>
                    <el-dropdown-menu slot='dropdown'>
                      <el-dropdown-item>
                        <el-link v-permission='3' underline={false} size='mini' onClick={() => this.openCircul(row, $index)}>
                          流转信息
                        </el-link>
                      </el-dropdown-item>
                      <el-dropdown-item>
                      {row.cstatus === 1 && (
                        <el-link v-permission='7' underline={false} size='mini' type='danger' onClick={() => this.openBackOrder(row, $index)}>
                          退单
                        </el-link>
                      )}
                      </el-dropdown-item>
                               <el-dropdown-item>
                      {row.cstatus === 5 && (
                        <el-link v-permission='10' underline={false} size='mini' type='danger' onClick={() => this.openBackOrderConfirm(row, $index)}>
                          退单确认
                        </el-link>
                      )}
                      </el-dropdown-item>
                      <el-dropdown-item>
                      {(row.cstatus === 1 || row.cstatus === 5) && (
                        <el-link v-permission='6' underline={false} size='mini' onClick={() => this.openTransferOrder(row, $index)}>
                          转派
                        </el-link>
                      )}
                      </el-dropdown-item>
                      <el-dropdown-item>
                      {(row.cstatus === 1 || row.cstatus === 5) && (
                        <el-link v-permission='2' underline={false} size='mini' onClick={() => this.openPressOrder(row, $index)}>
                          催单
                        </el-link>
                      )}
                      </el-dropdown-item>
                      <el-dropdown-item>
                        {row.cstatus === 1 && <el-link v-permission='4' underline={false} size='mini' onClick={() => this.dealConfirm(row, $index)}>
                          处理确认
                        </el-link>}
                      </el-dropdown-item>
                      <el-dropdown-item>
                        {row.cstatus === 2 && <el-link v-permission='5' underline={false} size='mini' onClick={() => this.openReturnVisit(row, $index)}>
                          回访
                        </el-link>}
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <el-link v-permission='8' underline={false} size='mini' onClick={() => this.openRemark(row, $index)}>
                          备注
                        </el-link>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              )
            }
          }
        ]
      }
    },
    watch: {
      $route: {
        handler: function(to, from) {
          this.reGetUrlParams()
        },
        deep: true
      }
    },
    async created() {
      await Promise.all([this.getCallCheckInfoList(), this.getTreeData(), this.getOwnersList(), this.queryData(), this.getComplaintTypeList(), this.getComplainStatus()])
      this.reGetUrlParams()
    },
    mounted() {
      // console.log('mounted')
      this.getComplaintCount()
      this.interval = setInterval(() => {
        this.getComplaintCount()
      }, 60000)
    },
    beforeDestroy() {
      // console.log('beforeDestroy')
      clearInterval(this.interval)
    },
    methods: {
      reGetUrlParams() {
        if (this.$route.query) {
          const urlParams = this.$route.query
          this.query.cstatus = urlParams.cstatus ? Number(urlParams.cstatus) : ''
        }
        this.search()
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.$set(this.query, 'userId', '')
        this.getOwnersList(value.orgId)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query.createTime = this.date[0]
          query.createTimeEnd = this.date[1]
        }
        query[this.csmType] = this.csmText
        if (this.callCheck.length > 0) query.callCheck = this.callCheck.join(',')
        else query.callCheck = ''
        const res = await queryComplaintManageList(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 查询是否有新的报修单
      async getComplaintCount() {
        const query = {
          cstatus: 1,
          createTime: parseTime(new Date(), '{y}-{m}-{d}'),
          currentPage: 1,
          pageSize: 1
        }
        const res = await queryComplaintManageList(query)
        if (res.data.total > 0) {
          const dom = document.getElementById('newComplain')
          dom.play()
        }
      },
      async  getComplaintTypeList() {
        const res = await getComplainType()
        if (res && res.data) {
          this.complaintTypeList = res.data
        }
      },
      // 查询处理人列表
      async getOwnersList(org) {
        this.ownersList = []
        this.query.userId = ''
        if (!org) return
        const res = await complainUserList({
          orgId: org
        })
        this.ownersList = res.data
      },
      // // 查询回访结果枚举
      // async getVisitStatusMap() {
      //   const res = await queryVisitStatusMap({})
      //   this.visitStatusMap = res.data
      // },
      async getCallCheckInfoList() {
        const res = await queryComplaintReturnVisitParams()
        this.commonKeysInfoList = JSON.parse(res.data.commonKeysInfoList)
      },
      async getComplainStatus() {
        const res = await getComplainStatus()
        if (res && res.data) {
          this.complaintStatusMap = res.data
        }
      },
      // 获取枚举
      async queryData() {
        const [res1, res2] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' })
        ])
        this.paymenFilList = res1.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 2048) // 支付方式
        this.calcTypeList = res2.data // 收款方式
      },
      async openDetail(row) {
        await this.$refs.detail.open(row)
      },
      // 点击客户编码
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row)
      },
      // 点击催单
      async openPressOrder(row) {
        await this.$refs.pressOrder.open({ billCode: row.complainId, billType: 4, text: '处理' })
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击处理确认
      async dealConfirm(row) {
        await this.$refs.dealConfirm.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击回访
      async openReturnVisit(row) {
        console.log(row)
        await this.$refs.returnVisit.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击流转信息
      async openCircul(row) {
        await this.$refs.flowInfo.open(row.complainId, 4)
      },
      // 点击退单
      async openBackOrder(row) {
        await this.$refs.backOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击退单确认
      async openBackOrderConfirm(row) {
        await this.$refs.backOrderConfirm.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击转派
      async openTransferOrder(row) {
        await this.$refs.transferOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击备注
      async openRemark(row) {
        await this.$refs.remarkOrder.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      exportFile() {
        const _this = this
        this.$confirm(`确定数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          queryExportComplaintList({
            paramInfo: _this._getQuery(_this.searchParams),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      searchClear() {
        if (this.$refs.treeSelect) this.$refs.treeSelect.keywords = ''
        if (this.$refs.treeSelect1) this.$refs.treeSelect1.keywords = ''
      },
      tableRowClassName({ row, rowIndex }) {
        console.log(row.auditingStatus, '----------')
        if (row.cstatus === 1 || row.cstatus === 5) {
          return 'r-row'
        } else {
          return ''
        }
      },
      async openComplaintDetail(row) {
        await this.$refs.complaintDetail.open(row)
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}

.complaintLbTable {

  /deep/ .el-table .r-row {
    background: #ffeced !important;
  }
}
</style>
